package com.wgh.pay.controller;

import com.wgh.pay.service.PayService;
import com.wgh.common.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 支付控制器
 */
@RestController
@RequestMapping("/api/pay")
public class PayController {
    
    @Autowired
    private PayService payService;
    
    /**
     * 创建支付订单
     * @param params 支付参数
     * @return 支付结果
     */
    @PostMapping("/create")
    public Result<?> createPayOrder(@RequestBody Map<String, Object> params) {
        try {
            Long orderId = Long.parseLong(params.get("orderId").toString());
            BigDecimal amount = new BigDecimal(params.get("amount").toString());
            Integer payType = Integer.parseInt(params.get("payType").toString());
            String clientIp = params.getOrDefault("clientIp", "127.0.0.1").toString();
            String notifyUrl = params.getOrDefault("notifyUrl", "").toString();
            
            Map<String, Object> result = payService.createPayOrder(orderId, amount, payType, clientIp, notifyUrl);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("创建支付订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询支付订单状态
     * @param orderId 订单ID
     * @return 支付订单状态
     */
    @GetMapping("/query/{orderId}")
    public Result<?> queryPayOrderStatus(@PathVariable Long orderId) {
        try {
            return Result.success(payService.queryPayOrderStatus(orderId));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询支付订单状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 支付结果通知（异步回调）
     * @param payType 支付方式
     * @param notifyData 通知数据
     * @return 通知结果
     */
    @PostMapping("/notify/{payType}")
    public String payNotify(@PathVariable Integer payType, 
                          @RequestBody(required = false) Map<String, String> notifyData, 
                          @RequestParam(required = false) Map<String, String> queryParams) {
        try {
            // 处理不同支付方式的通知数据格式
            Map<String, String> data = notifyData;
            if (data == null || data.isEmpty()) {
                data = queryParams;
            }
            
            boolean result = payService.handlePayNotify(data, payType);
            
            // 根据支付方式返回不同的成功响应
            if (result) {
                switch (payType) {
                    case 1: // 微信支付
                        return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    case 2: // 支付宝
                        return "success";
                    case 3: // 银联支付
                        return "{\"respCode\":\"00\",\"respMsg\":\"成功\"}";
                    default:
                        return "success";
                }
            } else {
                return "fail";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }
    
    /**
     * 关闭支付订单
     * @param orderId 订单ID
     * @return 关闭结果
     */
    @PostMapping("/close/{orderId}")
    public Result<?> closePayOrder(@PathVariable Long orderId) {
        try {
            boolean result = payService.closePayOrder(orderId);
            if (result) {
                return Result.success("订单已关闭");
            } else {
                return Result.error("订单关闭失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("关闭支付订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 发起退款
     * @param params 退款参数
     * @return 退款结果
     */
    @PostMapping("/refund")
    public Result<?> refund(@RequestBody Map<String, Object> params) {
        try {
            Long orderId = Long.parseLong(params.get("orderId").toString());
            BigDecimal refundAmount = new BigDecimal(params.get("refundAmount").toString());
            String refundReason = params.getOrDefault("refundReason", "").toString();
            
            Map<String, Object> result = payService.refund(orderId, refundAmount, refundReason);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发起退款失败：" + e.getMessage());
        }
    }
    
    /**
     * 查询退款状态
     * @param orderId 订单ID
     * @return 退款状态
     */
    @GetMapping("/refund/query/{orderId}")
    public Result<?> queryRefundStatus(@PathVariable Long orderId) {
        try {
            return Result.success(payService.queryRefundStatus(orderId));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询退款状态失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取支付渠道配置
     * @param payType 支付方式
     * @return 支付渠道配置
     */
    @GetMapping("/config/{payType}")
    public Result<?> getPayChannelConfig(@PathVariable Integer payType) {
        try {
            return Result.success(payService.getPayChannelConfig(payType));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取支付渠道配置失败：" + e.getMessage());
        }
    }
    
    /**
     * 统一支付接口
     * @param payParams 支付参数
     * @return 支付结果
     */
    @PostMapping("/unified")
    public Result<?> unifiedPay(@RequestBody Map<String, Object> payParams) {
        try {
            return Result.success(payService.unifiedPay(payParams));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("统一支付失败：" + e.getMessage());
        }
    }
}